package com.xiaojian.blog.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.vdurmont.emoji.EmojiParser;
import com.xiaojian.blog.constant.WebConstant;
import com.xiaojian.blog.dao.ContentPOMapper;
import com.xiaojian.blog.dao.MetaPOMapper;
import com.xiaojian.blog.dto.Types;
import com.xiaojian.blog.exception.TipException;
import com.xiaojian.blog.model.ContentPO;
import com.xiaojian.blog.model.ContentPOExample;
import com.xiaojian.blog.service.ContentService;
import com.xiaojian.blog.service.MetaService;
import com.xiaojian.blog.service.RelationshipService;
import com.xiaojian.blog.utils.DateKit;
import com.xiaojian.blog.utils.TaleUtils;
import com.xiaojian.blog.utils.Tools;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.lang.reflect.Type;
import java.util.List;


@Service
public class ContentServiceImpl implements ContentService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ContentServiceImpl.class);

    @Resource
    private MetaService metaService;

    @Resource
    private ContentPOMapper contentPOMapper;

    @Resource
    private RelationshipService relationshipService;

    @Resource
    private MetaPOMapper metaPOMapper;

    @Override
    @Transactional
    public String publish(ContentPO contentPO) {
        if (null == contentPO) {
            return "文章对象为空";
        }
        if (StringUtils.isBlank(contentPO.getTitle())) {
            return "文章标题不能为空";
        }
        if (StringUtils.isBlank(contentPO.getContent())) {
            return "文章内容不能为空";
        }
        int titleLength = contentPO.getTitle().length();
        if (WebConstant.MAX_TITLE_COUNT < titleLength) {
            return "文章标题过长";
        }
        int contentLength = contentPO.getContent().length();
        if (WebConstant.MAX_TEXT_COUNT < contentLength) {
            return "文章内容过长";
        }
        if (null == contentPO.getAuthorId()) {
            return "请登录后发布文章";
        }
        if (StringUtils.isNotBlank(contentPO.getSlug())) {
            if (contentPO.getSlug().length() < 5) {
                return "路径太短了";
            }
            if (!TaleUtils.isPath(contentPO.getSlug())) {
                return "您输入的路径不合法";
            }
            ContentPOExample contentPOExample = new ContentPOExample();
            contentPOExample.createCriteria().andTypeEqualTo(contentPO.getType())
                    .andStatusEqualTo(contentPO.getSlug());
            long count = contentPOMapper.countByExample(contentPOExample);
            if (count > 0) return "该路径已经存在,请重新输入";
        }else {
            //说明缩略名是空的
            contentPO.setSlug(null);
        }
        //将内容中的表情符号转化为字符
        contentPO.setContent(EmojiParser.parseToAliases(contentPO.getContent()));

        int time = DateKit.getCurrentUnixTime();
        contentPO.setCreated(time);
        contentPO.setModified(time);
        contentPO.setHits(0);
        contentPO.setCommentsNum(0);

        String tags = contentPO.getTags();
        String categories = contentPO.getCategories();
        contentPOMapper.insert(contentPO);
        Integer cid = contentPO.getCid();
        metaService.saveMetas(cid, tags, Types.TAG.getType());
        metaService.saveMetas(cid, categories, Types.CATEGORY.getType());
        return WebConstant.SUCCESS_RESULT;
    }

    @Override
    public PageInfo<ContentPO> getContents(Integer p, Integer limit) {
        LOGGER.debug("Enter getContents method");
        ContentPOExample example = new ContentPOExample();
        example.setOrderByClause("created desc");
        example.createCriteria().andTypeEqualTo(Types.ARTICLE.getType())
                .andStatusEqualTo(Types.PUBLISH.getType());
        PageHelper.startPage(p, limit);
        List<ContentPO> data = contentPOMapper.selectByExample(example);
        PageInfo<ContentPO> pageInfo = new PageInfo<>(data);
        LOGGER.debug("Exit getContents method");
        return pageInfo;
    }

    @Override//根据文章id查看文章
    public ContentPO getContents(String id) {
        if (StringUtils.isNotBlank(id)) {
            if (Tools.isNumber(id)) {
                ContentPO contentPO = contentPOMapper.selectByPrimaryKey(Integer.valueOf(id));
                return contentPO;
            }else {
                ContentPOExample contentPOExample = new ContentPOExample();
                contentPOExample.createCriteria().andSlugEqualTo(id);
                List<ContentPO> list = contentPOMapper.selectByExample(contentPOExample);
                if (list.size() != 1) {
                    throw new TipException("query content by id and return is not one");
                }
                return list.get(0);
            }
        }
        return null;
    }

    @Override//更新文章
    public void updateContentByCid(ContentPO contentPO) {
        if (null != contentPO && null != contentPO.getCid()) {
            contentPOMapper.updateByPrimaryKeySelective(contentPO);
        }
    }

    @Override//查询分类或者标签下面的文章归档
    public PageInfo<ContentPO> getArticles(Integer mid, int page, int limit) {
        Integer total = metaPOMapper.countWithSql(mid);
        PageHelper.startPage(page, limit);
        List<ContentPO> list = contentPOMapper.findByCatalog(mid);
        PageInfo<ContentPO> pageInfo = new PageInfo<>(list);
        pageInfo.setTotal(total);
        return pageInfo;
    }

    @Override//通过关键字分页搜索
    public PageInfo<ContentPO> getArticles(String keyword, Integer page, Integer limit) {
        PageHelper.startPage(page, limit);
        ContentPOExample example = new ContentPOExample();
        ContentPOExample.Criteria criteria = example.createCriteria();
        criteria.andTypeEqualTo(Types.ARTICLE.getType())
                .andSlugEqualTo(Types.PUBLISH.getType())
                .andTitleLike("%" + keyword + "%");
        example.setOrderByClause("created desc");
        List<ContentPO> list = contentPOMapper.selectByExampleWithBLOBs(example);
        return new PageInfo<ContentPO>(list);
    }

    @Override
    public PageInfo<ContentPO> getArticlesWithpage(ContentPOExample contentPOExample, Integer page, Integer limit) {
        PageHelper.startPage(page, limit);
        List<ContentPO> list = contentPOMapper.selectByExampleWithBLOBs(contentPOExample);
        return new PageInfo<ContentPO>(list);
    }

    @Override//根据文章id删除文章
    @Transactional
    public String deleteByCid(Integer cid) {
        ContentPO contentPO = this.getContents(cid + "");
        if (null != contentPO) {
            contentPOMapper.deleteByPrimaryKey(cid);
            relationshipService.deleteById(cid, null);
            return WebConstant.SUCCESS_RESULT;
        }
        return "数据为空";
    }

    @Override//编辑文章
    @Transactional
    public String updateArticle(ContentPO contentPO) {
        if (null == contentPO) {
            return "文章对象为空";
        }
        if (StringUtils.isBlank(contentPO.getTitle())) {
            return "文章标题不能为空";
        }
        if (StringUtils.isBlank(contentPO.getContent())) {
            return "文章内容不能为空";
        }
        int titleLength = contentPO.getTitle().length();
        if (titleLength > WebConstant.MAX_TITLE_COUNT) {
            return "文章标题过长";
        }
        int contentLength = contentPO.getContent().length();
        if (contentLength > WebConstant.MAX_TEXT_COUNT) {
            return "文章内容过长";
        }
        if (null == contentPO.getAuthorId()) {
            return "请登录后发表文章";
        }
        if (StringUtils.isBlank(contentPO.getSlug())) {
            contentPO.setSlug(null);
        }
        int time = DateKit.getCurrentUnixTime();
        contentPO.setModified(time);
        Integer cid = contentPO.getCid();
        contentPO.setContent(EmojiParser.parseToAliases(contentPO.getContent()));

        contentPOMapper.updateByPrimaryKeySelective(contentPO);
        relationshipService.deleteById(cid, null);
        metaService.saveMetas(cid, contentPO.getTags(), Types.TAG.getType());
        metaService.saveMetas(cid, contentPO.getCategories(), Types.CATEGORY.getType());
        return WebConstant.SUCCESS_RESULT;
    }

    @Override//更新原有文章的分类
    public void updateCategory(String ordinal, String newCategory) {
        ContentPO contentPO = new ContentPO();
        contentPO.setCategories(newCategory);
        ContentPOExample example = new ContentPOExample();
        example.createCriteria().andCategoriesEqualTo(ordinal);
        contentPOMapper.updateByExampleSelective(contentPO, example);
    }
}
